﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace TestProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string GetHTML(string url)
        {
            string tmp = "";
            Uri uri = new Uri(url);
            if (uri.Scheme == Uri.UriSchemeHttp)
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
                request.Method = WebRequestMethods.Http.Get;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                tmp = reader.ReadToEnd();
                response.Close();
            }
            return tmp;
        }
        private string GetDataByExpression(string url, string textRegex = "*")
        { 
            string content = GetHTML(url);
            string data = Regex.Match(content, textRegex, RegexOptions.IgnoreCase).Value;
            //Write2File(content);
            return data;
        }
        private void Write2File(string textData)
        {
            //Creating a new stream-writer and opening the file.
            TextWriter tsw = new StreamWriter(@"C:\Hello.txt");

            //Writing text to the file.
            tsw.WriteLine(textData);

            //Close the file.
            tsw.Close();
        }

        private void btnDoIt_Click(object sender, EventArgs e)
        {
            HtmlAgilityPack.HtmlDocument objDoc;
            HtmlDocumentLoader objLoader = new HtmlDocumentLoader();
            objDoc = objLoader.LoadDocument(txtURL.Text);
            
            var node = objDoc.DocumentNode.Descendants("h1").Where(
            d => d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("Title")).SingleOrDefault();
            //txtContent.Text = node.InnerText;



            var urls = objDoc.DocumentNode.Descendants("img")
                                .Select(m => m.GetAttributeValue("src", null))
                                .Where(s => !String.IsNullOrEmpty(s));

            foreach (string url in urls)
            {
                txtContent.Text += url + "\r\n";
            }
            //txtContent.Text = urls.ToString();
        }
    }
}
